package com.sts.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sts.dto.*;
import com.sts.entity.Ticket;
import com.sts.entity.TicketStatusFlow;
import com.sts.mapper.TicketMapper;
import com.sts.mapper.TicketStatusFlowMapper;
import com.sts.service.TicketService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class TicketServiceImpl implements TicketService {

    private final TicketMapper ticketMapper;
    private final TicketStatusFlowMapper statusFlowMapper;

    /* ---------- 创建 ---------- */
    @Override
    @Transactional
    public TicketDTO create(TicketCreateDTO dto, Long creatorId) {
        Ticket t = Ticket.builder()
                .title(dto.getTitle())
                .description(dto.getDescription())
                .type(dto.getType())
                .priority(dto.getPriority())
                .status("NEW")
                .creatorId(creatorId)
                .handlerId(null)
                .build();          // deleted 由逻辑删除默认值处理
        ticketMapper.insert(t);

        statusFlowMapper.insert(TicketStatusFlow.builder()
                .ticketId(t.getId())
                .fromStatus(null)
                .toStatus("NEW")
                .operatorId(creatorId)
                .remark("工单创建")
                .createdAt(LocalDateTime.now())
                .build());
        return toDTO(t);
    }

    /* ---------- 单条详情 ---------- */
    @Override
    public TicketDTO detail(Long id) {
        Ticket t = ticketMapper.selectById(id);   // 自动带 deleted = 0
        return t == null ? null : toDTO(t);
    }

    /* ---------- 列表 ---------- */
    @Override
    public List<TicketDTO> list() {
        // 只保留排序，逻辑删除由插件自动处理
        return ticketMapper.selectList(
                        Wrappers.<Ticket>lambdaQuery()
                                .orderByDesc(Ticket::getId))
                .stream()
                .map(this::toDTO)
                .collect(Collectors.toList());
    }

    /* ---------- 指派 ---------- */
    @Override
    @Transactional
    public void assign(TicketAssignDTO dto, Long operatorId) {
        Ticket t = ticketMapper.selectById(dto.getTicketId());
        if (t == null) throw new RuntimeException("工单不存在");

        t.setHandlerId(dto.getHandlerId());
        ticketMapper.updateById(t);   // 自动带 deleted = 0

        statusFlowMapper.insert(TicketStatusFlow.builder()
                .ticketId(dto.getTicketId())
                .fromStatus(t.getStatus())
                .toStatus(t.getStatus())
                .operatorId(operatorId)
                .remark("指派给：" + dto.getHandlerId())
                .createdAt(LocalDateTime.now())
                .build());
    }

    /* ---------- 状态更新 ---------- */
    @Override
    @Transactional
    public void updateStatus(TicketStatusUpdateDTO dto, Long operatorId) {
        Ticket t = ticketMapper.selectById(dto.getTicketId());
        if (t == null) throw new RuntimeException("工单不存在");

        t.setStatus(dto.getNewStatus());
        ticketMapper.updateById(t);

        statusFlowMapper.insert(TicketStatusFlow.builder()
                .ticketId(dto.getTicketId())
                .fromStatus(t.getStatus())
                .toStatus(dto.getNewStatus())
                .operatorId(operatorId)
                .remark(dto.getRemark())
                .createdAt(LocalDateTime.now())
                .build());
    }

    /* ---------- 内部转换 ---------- */
    private TicketDTO toDTO(Ticket t) {
        return BeanUtil.copyProperties(t, TicketDTO.class);
    }
}
